<template>
  <div class="base-pie-chart">
    <div class="chart-content">
      <div ref="chartRef" class="chart-container"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'

interface Props {
  title: string
  data: {
    series: {
      name: string
      data: number[]
    }[]
  }
}

const props = withDefaults(defineProps<Props>(), {
  title: '',
  data: () => ({
    series: []
  })
})

const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  const option = {
    title: {
      text: props.title
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      top: '12%',
      left: 10,
      data: props.data.series[0]?.data.map((_, index) => `Item ${index + 1}`) || []
    },
    series: [
      {
        name: props.data.series[0]?.name || 'Data',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: props.data.series[0]?.data.map((value, index) => ({
          name: `Item ${index + 1}`,
          value: value
        })) || []
      }
    ]
  }
  
  chart.setOption(option)
}

onMounted(() => {
  initChart();
  window.addEventListener("resize", handleResize);
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
  }
  window.removeEventListener("resize", handleResize);
})

watch(() => props.data, () => {
  if (chart) {
    initChart()
  }
}, { deep: true })

const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};
</script>

<style scoped>
.base-pie-chart {
  width: 100%;
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
  background: white;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.chart-content {
  width: calc(100% - 32px);
  height: calc(100% - 32px);
  display: flex;
  flex-direction: column;
}

h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.chart-container {
  flex: 1;
  width: 100%;
  height: 100%;
  /* min-height: 300px; */
  background: white;
}
</style> 